package cc.geguo.file;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import org.apache.struts2.ServletActionContext;

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by 13687 on 2017/1/9.
 * 1. 显示文件下载列表
 * 2. 显示下载文件
 */
public class FileDownload extends ActionSupport {

	public String list() throws  Exception{
//
		String path = ServletActionContext.getServletContext().getRealPath("/upload");
		File file = new File(path);
		String[] fileNames = file.list();

		ActionContext ac = ActionContext.getContext();
		Map<String, Object> request = ac.getContextMap();
		request.put("fileNames",fileNames);

		return "list";
	}

	public void setFileName(String fileName) {
		try {
			fileName = new String(fileName.getBytes("ISO8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		this.fileName = fileName;
	}

	//	文件下载
	private String fileName;


	public String down() throws Exception{
		return "download";
	}

//	返回文件流(在配置文件中设置了)
	public InputStream getAttrInputStream(){
		return ServletActionContext.getServletContext().getResourceAsStream("/upload/"+fileName);
	}
//	回显下载文件名称
	public String getDownFileName(){
		try {
			return URLEncoder.encode(fileName,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return fileName;
	}
}
